/**
 * 系统管理模块通用变更 Hook
 * 基于 useApiMutation 统一处理成功/失败提示、缓存失效与错误文案
 */

import { useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { useApiMutation } from '@/lib/api/hooks/use-api.js';
import { extractErrorMessage } from '@/lib/utils/api-error.js';

function normalizeInvalidateKey(key) {
  if (!key) return null;
  if (Array.isArray(key)) {
    return { queryKey: key };
  }
  if (typeof key === 'string') {
    return { queryKey: [key] };
  }
  if (typeof key === 'object' && key.queryKey) {
    return key;
  }
  return null;
}

export function useAdminMutation(mutationFn, options = {}) {
  const {
    successMessage,
    errorMessage,
    invalidateKeys = [],
    onSuccess,
    onError,
    ...restOptions
  } = options;

  const queryClient = useQueryClient();

  return useApiMutation(mutationFn, {
    showSuccessToast: false,
    showErrorToast: false,
    ...restOptions,
    onSuccess: async (data, variables, context) => {
      if (invalidateKeys.length > 0) {
        await Promise.all(
          invalidateKeys
            .map(normalizeInvalidateKey)
            .filter(Boolean)
            .map((config) => queryClient.invalidateQueries(config)),
        );
      }

      if (onSuccess) {
        await onSuccess(data, variables, context);
      }

      if (successMessage) {
        const message =
          typeof successMessage === 'function'
            ? successMessage(data, variables, context)
            : successMessage;
        if (message) {
          toast.success(message);
        }
      }
    },
    onError: (error, variables, context) => {
      if (onError) {
        onError(error, variables, context);
      }

      if (errorMessage !== false) {
        const message =
          typeof errorMessage === 'function'
            ? errorMessage(error, variables, context)
            : errorMessage;
        toast.error(message || extractErrorMessage(error, '操作失败'));
      }
    },
  });
}


